import { API_BASE_URL, DOMAIN } from '../lib/constants';

import axios from 'axios';
import cookies from 'js-cookie';
import { message } from 'antd';
import { redirectLoginPage } from '../service/auth';

const instance = axios.create({
  timeout: 30 * 1000, // 超时30s
  baseURL: API_BASE_URL,
  timeoutErrorMessage: '请求已超时',
  /*

   The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
   The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

   https://blog.csdn.net/chjj0904/article/details/90268813
  */
  // withCredentials: true,
});

const getMessage = (data) => data?.message || data?.msg || data?.info;

instance.interceptors.response.use(
  (res) => res.data,
  (error) => {
    const res = error.response;
    const msg = getMessage(res?.data) || '系统异常';

    if (res?.status === 401) {
      cookies.remove('token', { domain: DOMAIN });
      cookies.remove('uid', { domain: DOMAIN });
      redirectLoginPage();
      return;
    }

    message.warning(msg);
    // 在响应错误的时候的逻辑处理
    return Promise.reject(error);
  },
);

instance.interceptors.request.use((cfg) => {
  const token = cookies.get('token', { domain: DOMAIN });
  if (token) {
    cfg.headers.Authorization = `Bearer ${token}`;
  }
  cfg.params = {
    ...cfg.params,
    _: Date.now(),
  };
  return cfg;
});

export default instance;
